<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/plugin/layui/css/layui.css" media="all">
    <style>
        /*.layui-row div{*/
        /*    height: 28px;*/
        /*}*/

        label{
            margin-top: 20px;
            font-size: 20px;
        }
    </style>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>聊天室</legend>
</fieldset>
<div class="layui-container">
    <div class="layui-row ">
        <div class="layui-col-md6 layui-show-md-inline" id="onlineUser">
            当前用户：xxx
        </div>
        <div class="layui-col-md3 layui-show-md-inline" id="onlineUserNum">
            在线用户数：0
        </div>
        <div class="layui-col-md3 layui-show-md-inline">
            在线用户列表
        </div>
    </div>

    <div class="layui-row layui-fluid">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                <legend>聊天内容</legend>
            </fieldset>

            <div class="layui-row">
                <div class="layui-col-md9 layui-show-md-inline" id="chatContent" style="height: 666px;">
                    <!--  聊天内容列：-->
                </div>
                <div class="layui-col-md3 layui-show-md-inline" style="border: 1px solid red;height: 666px;" id="onlineUsers">
                        <!-- <label><input type="radio" name="onlineUserName" value="All" title="全部">全部</label>-->
                </div>
            </div>
        </div>
        <div class="layui-row layui-form" style="margin-top: 20px;">
            <div class="layui-col-md9 layui-inline"><input type="text" id="message" value="" class="layui-input" onkeydown="if(event.keyCode==13) {send()}"/></div>
            <button type="button" class="layui-btn layui-btn-primary" onclick="send()">发送</button>
        </div>

    </div>


</div>
</body>
<script src="/plugin/jquery/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="/plugin/layui/layui.js" charset="utf-8" type="text/javascript"></script>

<script type="text/javascript">

    var webSocket;
    var userName = "";

    //初始化表格
    var form,layer;
    layui.use(['form','layer'], function() {
             form = layui.form
            , layer = layui.layer;
    });


    $.post("/chat/getUserName",{},function (data) {
        userName = data;
        $("#onlineUser").text(" 当前用户："+userName);
        initChatWebsocke();
    });

    function initChatWebsocke() {
        if ("WebSocket" in window)
        {
            webSocket = new WebSocket("ws://localhost:8080/chatWebSocket/"+userName);

            //连通之后的回调事件
            webSocket.onopen = function()
            {
                //webSocket.send( document.getElementById('username').value+"已经上线了");
                console.log("已经连通了websocket");
                setMessageInnerHTML(userName+"已上线！");
            };

            //接收后台服务端的消息
            webSocket.onmessage = function (evt)
            {
                var received_msg = evt.data;
                console.log("数据已接收:" +received_msg);
                var obj = JSON.parse(received_msg);
                console.log("可以解析成json:"+obj.messageType);
                //1代表上线 2代表下线 3代表在线名单 4代表普通消息
                if(obj.messageType==1){
                    //把名称放入到selection当中供选择
                    var onlineName = obj.userName;
                    var onlineUserHtml ="<label><input type=\"radio\" name=\"onlineUserName\" value=\""+onlineName+"\" title=\""+onlineName+"\">"+onlineName+"</label><br/>"
                    $("#onlineUsers").append(onlineUserHtml);
                    $("#onlineUserNum").text("在线用户数："+obj.onlineNumber);
                    setMessageInnerHTML(onlineName+"上线了");
                }
                else if(obj.messageType==2){
                    var onlineName = obj.onlineUsers;
                    var offlineName = obj.userName;
                    var onlineUserHtml = "<label><input type=\"radio\" name=\"onlineUserName\" value=\"All\" title=\"全部\" checked>全部</label><br/>\n";
                    $("#onlineUsers").empty();
                    for(var i=0;i<onlineName.length;i++){
                        if(!(onlineName[i]==userName)){
                            onlineUserHtml +="<label><input type=\"radio\" name=\"onlineUserName\" value=\""+onlineName[i]+"\" title=\""+onlineName[i]+"\">"+onlineName[i]+"</label><br/>"
                        }
                    }
                    $("#onlineUsers").append(onlineUserHtml);
                    $("#onlineUserNum").text("在线用户数："+obj.onlineNumber);
                    setMessageInnerHTML(offlineName+"下线了");
                }
                else if(obj.messageType==3){
                    var onlineName = obj.onlineUsers;
                    $("#onlineUserNum").text("在线用户数："+obj.onlineNumber);
                    var onlineUserHtml = "<label><input type=\"radio\" name=\"onlineUserName\" value=\"All\" title=\"全部\" checked>全部</label><br/>\n";
                    $("#onlineUsers").empty();
                    for(var i=0;i<onlineName.length;i++){
                            onlineUserHtml +="<label><input type=\"radio\" name=\"onlineUserName\" value=\""+onlineName[i]+"\" title=\""+onlineName[i]+"\">"+onlineName[i]+"</label><br/>"
                    }
                    $("#onlineUsers").append(onlineUserHtml);
                    console.log("获取了在线的名单"+onlineName.toString());
                }else{ //普通消息
                    console.log(obj);
                    setMessageInnerHTML(obj.userName+"对"+obj.toUserName+"说："+obj.message);
                }
            };

            //连接关闭的回调事件
            webSocket.onclose = function()
            {
                console.log("连接已关闭...");
                setMessageInnerHTML("连接已经关闭....");
            };
        }else{
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }


    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        //document.getElementById('message').innerHTML += innerHTML + '<br/>';
        let messageContent = " <div class=\"layui-col-md12\" style=\"margin-top: 20px;\">\n"+innerHTML +"</div>";
        $("#chatContent").append(messageContent);
    }

    function closeWebSocket() {
        //直接关闭websocket的连接
        webSocket.close();
    }

    //发送消息
    function send() {
        var selectText = $("input[name='onlineUserName']:checked").val();
        var sendMessage = {
            "message":$("#message").val(),
            "userName":userName,
            "toUserName":selectText
        };
        webSocket.send(JSON.stringify(sendMessage));
        if(selectText != "All"){
            setMessageInnerHTML(sendMessage.userName+"对"+sendMessage.toUserName+"说："+sendMessage.message);
        }
        $("#message").val("");
    }

</script>
</html>